﻿using System;
using System.Collections.Generic;

namespace rehot.core
{
    using SanlieHash;

    internal class HotResourceBox
    {
        internal Dictionary<ushort, string> namesmap { get; set; }
        internal Dictionary<string, string> res_map { get; set; }
        internal Dictionary<string, string> fullnamesmap { get; set; }
        internal ushort id = 0;
        internal void Lose()
        {
            if (fullnamesmap != null) fullnamesmap.Clear();
            if (namesmap != null) namesmap.Clear();
            fullnamesmap = null;
            namesmap = null;
        }
        public HotResourceBox()
        {
            namesmap = new Dictionary<ushort, string>();
            fullnamesmap = new Dictionary<string, string>();
            res_map = new Dictionary<string, string>();
        }
        public void Clear()
        {
            id = 0;
            if (namesmap.Count > 0 || fullnamesmap.Count > 0)
            {
                namesmap.Clear();
                fullnamesmap.Clear();
            }
        }
        public void Add(string name)
        {
            //rehot.core.filename
            var iid = ++id;
            var ix = -1;
            var res_id = FastHash.GetSM3(name);
            namesmap[iid] = res_id;
            if (!res_map.ContainsKey(res_id)) res_map.Add(res_id, name);
            while ((ix = name.IndexOf(".")) >= 0)
            {
                name = name.Substring(ix+1);
                var hash = FastHash.GetSM3(name.ToLower());
                if (!fullnamesmap.ContainsKey(hash)) fullnamesmap[hash] = string.Empty;
                fullnamesmap[hash] += string.Empty + (char)(id >> 8) + (char)id;
            }
        }

        internal IEnumerable<ushort> readuints(string data)
        {
            for (int i = 0; i < data.Length; i += 2) yield return (ushort)((ushort)((byte)data[i] << 8) | (byte)data[i + 1]);
        }
        public string FindById(string id)
        {
            if (res_map.ContainsKey(id)) return res_map[id];
            return string.Empty;
        }

        public string FindId(string filename)
        {
            var hash = FastHash.GetSM3(filename.ToLower());
            if (fullnamesmap.ContainsKey(hash)) foreach (var id in readuints(fullnamesmap[hash])) return namesmap[id];
            return string.Empty;
        }
        public IEnumerable<string> FindIds(string filename)
        {
            var hash = FastHash.GetSM3(filename.ToLower());
            if (fullnamesmap.ContainsKey(hash)) foreach (var id in readuints(fullnamesmap[hash])) yield return namesmap[id];
        }
    }
}
